// Includes
#include "Turret.h"

//Struct Function
bool Bullet::checkCollision(float x, float y, OBJ_TYPE obj)
{
	//JJ Test if character is colliding with door
	float	px, py, // Character Center
			ox, oy; // Object Center

	// Calculate Character Center
	px = posX + (SPRITE_SIZE / 2);
	py = posY + (15 / 2);

	// Calculate Object Center
	ox = x + (SPRITE_SIZE / 2);
	oy = y + (15 / 2);

	float difX = px - ox;
	float difY = py - oy;

	if(abs(difX) <= SPRITE_SIZE && abs(difY) <= SPRITE_SIZE) 
		return true;

	return false;
}

// Constructor
Turret::Turret()
{
	isActive = false;
	canFire  = true;
	secDif = 0.0;
	dir = 0; //Inactive

	bullet.isActive = false;
	bullet.posX = posX;
	bullet.posY = posY;
	bullet.speed = 0.9f;
}

//Functions
void Turret::updateBullets()
{
	if(bullet.isActive)
	{
		switch(dir)
		{
		case 1:
			bullet.posY -= bullet.speed;
			break;
		case 2:
			bullet.posX -= bullet.speed;
			break;
		case 3:
			bullet.posX += bullet.speed;
			break;
		case 4:
			bullet.posY += bullet.speed;
			break;
		}
	}
}

void Turret::fire(FMOD::System* fmod,FMOD::Sound* sound,FMOD::Channel* ch)
{
	if(canFire)
	{
		canFire = false;
		
		bullet.isActive = true;

		switch(dir)
		{
		case 1:
			bullet.posX = posX;
			bullet.posY = posY - SPRITE_SIZE;
			break;
		case 2:
			bullet.posX = posX - SPRITE_SIZE;
			bullet.posY = posY;
			break;
		case 3:
			bullet.posX = posX + SPRITE_SIZE;
			bullet.posY = posY;
			break;
		case 4:
			bullet.posX = posX;
			bullet.posY = posY + SPRITE_SIZE;
			break;
		}
		
		lastFired = time(NULL);
		fmod->playSound(FMOD_CHANNEL_FREE, sound, false, &ch);
	}
	else if(!bullet.isActive)
	{
		currentTime = time(NULL);
		secDif = difftime(currentTime, lastFired);

		if(secDif > 0.6)
			canFire = true;
	}
}